// app/src/main/java/com/example/snake/ScoreManager.java
package com.example.snake;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ScoreManager {
    private static final String PREF_NAME = "snake_scores";
    private static final String SCORES_KEY = "scores";
    private static final int MAX_SCORES = 20;

    private SharedPreferences sharedPreferences;
    private Gson gson;

    public ScoreManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    public void saveScore(int score) {
        List<Integer> scores = getScores();
        scores.add(score);
        Collections.sort(scores, Collections.reverseOrder());

        // 只保留前20个最高分
        if (scores.size() > MAX_SCORES) {
            scores = scores.subList(0, MAX_SCORES);
        }

        String json = gson.toJson(scores);
        sharedPreferences.edit().putString(SCORES_KEY, json).apply();
    }

    public List<Integer> getScores() {
        String json = sharedPreferences.getString(SCORES_KEY, null);
        if (json != null) {
            Type type = new TypeToken<List<Integer>>(){}.getType();
            List<Integer> scores = gson.fromJson(json, type);
            return scores != null ? scores : new ArrayList<>();
        }
        return new ArrayList<>();
    }
}
